<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="identityVerification.name">
        <el-input
          v-model="queryParams['identityVerification.name']"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
          @clear="handleQuery"
          @input="onSearchInput('identityVerification.name')"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="carNum">
        <el-input
          v-model="queryParams.carNum"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
          @clear="handleQuery"
          @input="onSearchInput('carNum')"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['user:carinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['user:carinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['user:carinfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['user:carinfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车辆主键" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="identityVerification.name" />
      <el-table-column label="车型" align="center" prop="type" />
      <el-table-column label="车牌号" align="center" prop="carNum" />
      <el-table-column label="车辆照片" align="center" width="100">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.carImg" :src="scope.row.carImg" :width="50" :height="50"/>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['user:carinfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['user:carinfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户车辆对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="form.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="车型" prop="type">
          <el-input v-model="form.type" placeholder="请输入车型" />
        </el-form-item>
        <el-form-item label="车牌号" prop="carNum">
          <el-input v-model="form.carNum" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="车辆照片" prop="carImg">
          <image-upload v-model="form.carImg"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCarinfo, getCarinfo, delCarinfo, addCarinfo, updateCarinfo } from "@/api/user/carinfo"
import { listIdentity } from"@/api/merchant/identity"
import ImageUpload from "@/components/ImageUpload"
import ImagePreview from "@/components/ImagePreview"

export default {
  name: "Carinfo",
  components: {
    ImageUpload,
    ImagePreview
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户车辆表格数据
      carinfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //认证中心列表
      identityVerificationList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        uid: null,
        'identityVerification.name':null,
        type: null,
        carNum: null,
        carImg: null,
        isdefault: null,
        del: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "车型不能为空", trigger: "blur" }
        ],
        carNum: [
          { required: true, message: "车牌号不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.queryIdentityList()
  },
  methods: {
    /** 查询用户车辆列表 */
    getList() {
      this.loading = true
      console.log('车辆信息查询参数:', this.queryParams)
      listCarinfo(this.queryParams).then(response => {
        console.log('车辆信息API响应:', response)
        this.carinfoList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(error => {
        console.error('车辆信息查询失败:', error)
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        uid: null,
        name: null,
        type: null,
        carNum: null,
        carImg: null,
        isdefault: null,
        del: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加用户车辆"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCarinfo(id).then(response => {
        this.form = response.data
        // 如果有关联的认证信息，显示用户名
        if (this.form.identityVerification && this.form.identityVerification.name) {
          this.form.name = this.form.identityVerification.name
        }
        this.open = true
        this.title = "修改用户车辆"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查认证中心数据是否已加载
          if (this.identityVerificationList.length === 0) {
            this.$modal.msgWarning("认证中心数据正在加载中，请稍后再试...")
            return
          }

          console.log('提交表单数据:', this.form)
          console.log('认证中心列表:', this.identityVerificationList)
          console.log('查找用户名:', this.form.name)

          // 根据用户名查找用户ID
          const identity = this.identityVerificationList.find(item => item.name === this.form.name)
          console.log('找到的用户信息:', identity)

          if (identity) {
            this.form.uid = identity.id
            console.log('设置用户ID:', this.form.uid)
          } else {
            this.$modal.msgError(`未找到该用户名对应的用户信息。请输入的用户名是："${this.form.name}"，请检查认证中心是否有该用户。`)
            return
          }

          this.submitData()
        }
      })
    },
    /** 提交数据 */
    submitData() {
      if (this.form.id != null) {
        updateCarinfo(this.form).then(response => {
          this.$modal.msgSuccess("修改成功")
          this.open = false
          this.getList()
        })
      } else {
        addCarinfo(this.form).then(response => {
          this.$modal.msgSuccess("新增成功")
          this.open = false
          this.getList()
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除用户车辆编号为"' + ids + '"的数据项？注意：删除车辆信息会同时删除相关的订单记录！').then(function() {
        return delCarinfo(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch((error) => {
        // 只显示用户友好的错误信息，不显示技术性错误
        this.$modal.msgError("删除失败：该车辆信息有关联的订单记录，请先删除相关订单后再删除车辆信息")
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('user/carinfo/export', {
        ...this.queryParams
      }, `carinfo_${new Date().getTime()}.xlsx`)
    },
    // 查询认证中心列表
    queryIdentityList() {
      console.log('开始查询认证中心列表...')
      listIdentity().then(resp => {
        console.log('认证中心API响应:', resp)
        if (resp.code === 200) {
          this.identityVerificationList = resp.rows
          console.log('认证中心列表数据:', this.identityVerificationList)
          console.log('认证中心列表长度:', this.identityVerificationList.length)
        } else {
          console.error('认证中心API调用失败:', resp)
        }
      }).catch(error => {
        console.error('认证中心API调用异常:', error)
      })
    },
    /** 搜索输入监听 - 清空时自动查询 */
    onSearchInput(field) {
      const v = this.queryParams[field]
      if (v === '' || v == null) {
        this.queryParams.pageNum = 1
        this.getList()
      }
    }
  }
}
</script>
